package com.douleka.curd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.douleka.curd.entity.Announcement;
import com.douleka.curd.mapper.AnnouncementMapper;
import com.douleka.curd.service.IAnnouncementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douleka.curd.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 公告表 服务实现类
 * </p>
 *
 * @author hg
 * @since 2024-03-18
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements IAnnouncementService {

    //查询
    @Override
    public Result<Object> get(Integer curr, Integer pageSize, String title, Integer type, Integer readers) {
        Page<Announcement> announcementPage = new Page<>(curr,pageSize);
        QueryWrapper<Announcement> announcementQueryWrapper = new QueryWrapper<>();
        announcementQueryWrapper.like(StringUtils.hasText(title),"title",title)
                .eq(type!=null,"type",type)
                .eq(readers!=null,"readers",readers)
                .eq("status","0");
        page(announcementPage,announcementQueryWrapper);
        Map<String,Object> map = new HashMap<>();
        map.put("list",announcementPage.getRecords());
        map.put("totalCount",announcementPage.getTotal());
        map.put("totalPage",announcementPage.getPages());
        return new Result<>("200","成功",map);
    }

    //添加
    @Override
    public Result<Object> add(Announcement announcement) {
        announcement.setDate(LocalDateTime.now());
        announcement.setAdmin("admin");
        announcement.setModelId("1");
        if (!save(announcement)){
            return new Result<>("400","失败");
        }
        return new Result<>("200","成功");
    }

    //删除
    @Override
    public Result<Object> delete(Integer id) {
        UpdateWrapper<Announcement> announcementUpdateWrapper = new UpdateWrapper<>();
        announcementUpdateWrapper.eq("id",id).set("status","1");
        if (!update(announcementUpdateWrapper)){
            return new Result<>("400","失败");
        }
        return new Result<>("200","成功");
    }

    //修改
    @Override
    public Result<Object> update(Announcement announcement) {
        if (!updateById(announcement)){
            return new Result<>("400","失败");
        }
        return new Result<>("200","成功");
    }
}
